# -*- coding:utf-8 -*-
# Create your tasks here

from celery import shared_task
from django.conf import settings
from django.core.cache import cache
import logging
import requests, json
from Apps.UITest.models import uiCaseLog
from Apps.UITest.uiSelenium.runner import Runner

logger = logging.getLogger("django")

# redis 命令类
# from django_redis.client.default import DefaultClient
from django_redis import get_redis_connection

redis_conn = get_redis_connection("default")


@shared_task
def runUiTestTask():
    """
    从redis中取执行的ID，判断是否有空闲的session可用，有可用时，再执行
    :return: 返回执行Ui测试的名称
    """
    logger.info("UiTestList:任务执行")

    def session():
        result = requests.get(settings.DRIVER_HUB+"/status")
        resultData = json.loads(result.text)
        ready = resultData["value"]["ready"]
        if ready:
            nodes = resultData["value"]["nodes"]
            for node in nodes:
                maxSessions = node["maxSessions"]
                slots = node["slots"]
                slotNum = 0
                for slot in slots:
                    session = slot["session"]
                    if session:
                        slotNum += 1
                if slotNum < maxSessions:
                    return True

    if session():
        # 从缓存中获取，
        UiTestId = redis_conn.lpop("UiTestList") if getattr(settings, "REDIS_ENABLE", False) else ""
        if UiTestId:
            # 原始取出来是byte类型，需要自己decode
            logger.info(UiTestId.decode())
            UiTestId = UiTestId.decode()
            caseLogInstance = uiCaseLog.objects.get(id=UiTestId)
            Runner(caseLogInstance.run_case_data,UiTestId)
            return UiTestId
    return ""
